package leetcode211

// 解答失败:
//测试用例:["WordDictionary","addWord","addWord","search","search","search","search","search","search"] [[],["a"],["a"],["."],["a"],["aa"],["a"],[".a"],["a."]]
//测试结果:[null,null,null,true,true,false,true,false,true]
//期望结果:[null,null,null,true,true,false,true,false,false] stdout:

//  测试用例:["WordDictionary","addWord","addWord","search","search","search","search","search","search"]
//  [[],["a"],["a"],["."],["a"],["aa"],["a"],[".a"],["a."]]
//  测试结果:[null,null,null,true,true,false,true,false,true]
//  期望结果:[null,null,null,true,true,false,true,false,false] stdout:

type WordDictionary struct {
	list  [26]*WordDictionary
	isEnd bool
}

/** Initialize your data structure here. */
func Constructor() WordDictionary {
	return WordDictionary{}
}

func (this *WordDictionary) AddWord(word string) {
	cur := this
	for _, b := range word {
		if cur.list[b-'a'] == nil {
			cur.list[b-'a'] = new(WordDictionary)
		}
		cur = cur.list[b-'a']
	}
	cur.isEnd = true
	return
}

func (this *WordDictionary) Search(word string) bool {
	var searchHelp func(word string, node *WordDictionary) bool
	searchHelp = func(word string, node *WordDictionary) bool {
		for i := range word {
			if word[i] == '.' {
				for _, dictionary := range node.list {
					if dictionary != nil {
						if searchHelp(word[i+1:], dictionary) { //遇到'.'的时候跳过'.'继续匹配接下来的字符，树的深度进1
							return true
						}
					}
				}
				return false
			}
			if node.list[word[i]-'a'] == nil {
				return false
			} else {
				node = node.list[word[i]-'a']
			}
		}
		return node.isEnd
	}
	return searchHelp(word, this)
}
